package com.ice.app.project.generator.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iceframework.core.entity.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ice.app.project.generator.service.GeneratorService;
import com.ice.app.project.generator.utils.DateUtils;
import com.iceframework.core.entity.Result;
import com.iceframework.core.utils.CommonUtils;

/**
 * 自动生成工具
 * 
 * @author Palo
 *
 */
@Controller
@RequestMapping("/generator")
public class GeneratorController {

	@Autowired
	private GeneratorService generatorService;

	/**
	 * 列表展示
	 * 
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/list")
	public Result list(String tableName, Page<String> page, HttpServletRequest request) throws Exception {
		PageHelper.startPage(page.getPageNum(), page.getPageSize(), page.getOrderBy());
		List<Map<String, Object>> tableLists = generatorService.getTableAttribute(tableName);
		PageInfo<Map<String, Object>> data = new PageInfo<Map<String, Object>>(tableLists, page.getPageSize());
		return Result.success().add("data", data);
	}

	/**
	 * 生成代码
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/gencode")
	public void gencode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String[] tableNames = new String[] {};
		String tables = request.getParameter("tables");
		tableNames = tables.split(",");

		byte[] data = generatorService.generatorCode(tableNames);

		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"ice-code-" + DateUtils.format(new Date())
				+ "-" + CommonUtils.getStringRandom(4) + ".zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}
}
